package com.customization.unionpay.market.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.service.impl.ExternalFundingActivityServiceImpl;
import com.engine.cube.biz.ShardingActionHelper;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sjm
 * @description 营销日报表台账相关
 */
public class DailyReportRelated {

    private static final Logger log = LoggerFactory.getLogger(DailyReportRelated.class);

    /**
     * 根据授权码、日报流水类型、资金来源和表单表名获取营销活动日报表台账信息
     * @param authCode
     * @return
     */
    public static List<JSONObject> selectInfoByAuthCode(String authCode, String selectValuerRblslxError, String selectValuerRblslxNormal, String selectValueFundSourceRB, String reportFormTableName) throws Exception {
        RecordSet rs = new RecordSet();
        List<JSONObject> results = new ArrayList<>();
        try {
            if(StrUtil.isNotBlank(selectValueFundSourceRB)) {
                if (StrUtil.isNotBlank(reportFormTableName)) {
                    if(StrUtil.isNotBlank(selectValuerRblslxError) && StrUtil.isNotBlank(selectValuerRblslxNormal)){
                        // 营销平台活动授权码        yxpthdsqm
                        // 清算金额                qsje
                        // 日报流水类型             rblslx
                        // 营销平台事项申请单号      yxptsxsqdh
                        // 内部使用比例             nbsybl
                        // 资金来源                zjly

                        // 清算金额 * 出资比例 = 入账金额
                        String sql = "select id,qsje,rblslx,yxptsxsqdh from #{tableName} where 1=1 and yxpthdsqm=? and zjly=? and rblslx=? ";
                        sql = sql.replace("#{tableName}",reportFormTableName);
                        log.info("sql:"+sql);
                        rs.executeQuery(sql,authCode,selectValueFundSourceRB,selectValuerRblslxError);
                        while (rs.next()) {
                            JSONObject result = new JSONObject();
                            result.put("id", Util.null2String(rs.getString("id")));
                            result.put("qsje", Util.null2String(rs.getString("qsje")));
                            result.put("yxptsxsqdh", Util.null2String(rs.getString("yxptsxsqdh")));
                            results.add(result);
                        }
                    }else {
                        throw new Exception("查询获取营销活动日报表台账日报流水类型枚举异常!");
                    }
                } else {
                    throw new Exception("查询获取营销活动日报表台账主表表名异常!");
                }
            } else {
                throw new Exception("查询获取营销活动日报表台账资金来源枚举异常!");
            }
        }catch (Exception e){
            throw new Exception("查询异常："+e.getMessage());
        }
        return results;
    }

    /**
     * 根据id修改日报流水类型
     * @param id
     * @param selectValuerRblslxNormal
     * @param reportFormTableName
     * @return
     */
    public static void updateRblslx(String id,String selectValuerRblslxNormal,String reportFormTableName) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            String sql = "update #{tableName} set rblslx=?,ycxx='' where id=? ";
            sql = sql.replace("#{tableName}",reportFormTableName);
            log.info("sql:"+sql);
            // 修改日报流水类型
            rst.executeUpdate(sql,selectValuerRblslxNormal,id);
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改日报流水类型异常："+e.getMessage());
        }
    }

    /**
     * 修改符合类型数据的申请单号
     * @param authCode
     * @param code                            申请单号
     * @param selectValueFundSourceRB
     * @param reportFormTableName
     * @return
     */
    public static void updateBdh(String authCode,String code,String selectValueFundSourceRB,String reportFormTableName) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            String sql = "update #{tableName} set yxptsxsqdh=? where yxpthdsqm=? and zjly=? ";
            sql = sql.replace("#{tableName}",reportFormTableName);
            log.info("sql:"+sql);
            // 修改日报表申请单号
            rst.executeUpdate(sql,code,authCode,selectValueFundSourceRB);
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改申请单号异常："+e.getMessage());
        }
    }

    /**
     * 添加日报表数据
     * @param formId
     * @param formmodeId
     * @param user
     * @param maintablename
     * @param yxpthdsqm
     * @param actNm
     * @param actTotalAt
     * @param ptqdrq
     * @param jbr
     * @param zbdw
     * @param qsje
     * @param actTp
     * @param zjly
     * @param qsrq
     * @param sjly
     * @param rblslx
     * @param zt
     * @param ycxx
     */
    public static void addDailyReportData(int formId, int formmodeId,User user, String maintablename,
                                          String yxpthdsqm, String actNm, String actTotalAt,
                                          String ptqdrq, String jbr, String zbdw, String qsje,
                                          String actTp, String zjly, String qsrq, String sjly,
                                          String nbsybl, String yxptsxsqdh, String rblslx, String zt, String ycxx,String zjzhlx,String hdjsbs){

        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        // 先调用内部方法新建一条数据，获取数据id
        int billid = FormDataUtils.getBillId(maintablename, formmodeId, user.getUID(), user.getType());

        try {
            // 获取formbizid
            String formBizId = ShardingActionHelper.constructBizId(billid, formId);

            // 根据当前信息使用id修改新建数据
            StringBuilder updateSql = new StringBuilder(" update " );
            updateSql.append(maintablename);
            updateSql.append(" set yxpthdsqm='");
            updateSql.append(yxpthdsqm);
            if(actNm != null && !"".equals(actNm)) {
                updateSql.append("', ACT_NM='");
                updateSql.append(actNm);
            }
            if(actTotalAt != null && !"".equals(actTotalAt)) {
                updateSql.append("', ACT_TOTAL_AT='");
                updateSql.append(actTotalAt);
            }
            updateSql.append("', ptqdrq='");
            updateSql.append(ptqdrq);
            if(jbr != null && !"".equals(jbr)) {
                updateSql.append("', jbr='");
                updateSql.append(jbr);
            }
            if(zbdw != null && !"".equals(zbdw)) {
                updateSql.append("', zbdw='");
                updateSql.append(zbdw);
            }
            updateSql.append("', qsje='");
            updateSql.append(qsje);
            updateSql.append("', ACT_TP='");
            updateSql.append(actTp);
            updateSql.append("', zjly='");
            updateSql.append(zjly);
            updateSql.append("', qsrq='");
            updateSql.append(qsrq);
            updateSql.append("', sjly='");
            updateSql.append(sjly);
            if(nbsybl != null && !"".equals(nbsybl)) {
                updateSql.append("', nbsybl='");
                updateSql.append(nbsybl);
            }
            if(yxptsxsqdh != null && !"".equals(yxptsxsqdh)) {
                updateSql.append("', yxptsxsqdh='");
                updateSql.append(yxptsxsqdh);
            }
            updateSql.append("', rblslx='");
            updateSql.append(rblslx);
            updateSql.append("', zt='");
            updateSql.append(zt);
            if(ycxx != null && !"".equals(ycxx)) {
                updateSql.append("', ycxx='");
                updateSql.append(ycxx);
            }
            if(zjzhlx != null && !"".equals(zjzhlx)) {
                updateSql.append("', zjzhlx='");
                updateSql.append(zjzhlx);
            }
            updateSql.append("', hdjsbs='");
            updateSql.append(hdjsbs);
            updateSql.append("', form_biz_id='");
            updateSql.append(formBizId);
            updateSql.append("' where id='");
            updateSql.append(billid);
            updateSql.append("' ");
            log.info("updateSql:"+updateSql.toString());

            rst.executeUpdate(updateSql.toString());
            // 提交事务
            rst.commit();

            // 权限重构
            ModeRightInfo modeRightInfo = new ModeRightInfo();
            modeRightInfo.setNewRight(true);
            modeRightInfo.editModeDataShare(user.getUID(), formmodeId, billid);

            String zjlyDetails = FormDataUtils.getItemName(formId, "zjly", zjly);
            log.info("判断是否需要同步外部出资台账:"+zjlyDetails);
            if("外部营销".equals(zjlyDetails)){
                log.info("UID：" + user.getUID()+",Type："+user.getType());
                externalUpdateInfo(user,null,null,null,null,null,null,null,null,null,null,null,null,yxpthdsqm,null);
            }

        } catch (Exception e) {
            // 回滚
            rst.rollback();
            ClearFundButtonRelated.deleteByBillId(maintablename, billid);
            log.error("添加数据异常："+e.getMessage());
        }
    }

    /**
     * 根据ids获取营销活动日报表台账信息
     * @param reportFormTableName
     * @param ids
     * @return
     */
    public static List<JSONObject> selectDailyReportInfoByIds(String reportFormTableName,String ids) throws Exception {
        ids = ids.replace(",","','");
        log.info("ids:"+ids);
        RecordSet rs = new RecordSet();
        List<JSONObject> results = new ArrayList<>();
        try {
            // 资金来源  zjly
            // 活动类型  ACT_TP
            // 入账金额                rzje
            // 营销平台活动授权码        yxpthdsqm
            // 日报流水类型             rblslx
            // 营销平台事项申请单号      yxptsxsqdh

            String sql = "select id, yxpthdsqm, zjly, ACT_TP, rblslx, rzje, sqmwh, zt, yxptsxsqdh,jbr, qsrq, qsje, zjzhlx from #{tableName} where id in ('"+ids+"') ";
            sql = sql.replace("#{tableName}",reportFormTableName);
            log.info("sql:"+sql);
            rs.executeQuery(sql);
            while (rs.next()) {
                JSONObject result = new JSONObject();
                result.put("id", Util.null2String(rs.getString("id")));
                result.put("yxpthdsqm", Util.null2String(rs.getString("yxpthdsqm")));
                result.put("zjly", Util.null2String(rs.getString("zjly")));
                result.put("ACT_TP", Util.null2String(rs.getString("ACT_TP")));
                result.put("rblslx", Util.null2String(rs.getString("rblslx")));
                result.put("rzje", Util.null2String(rs.getString("rzje")));
                result.put("sqmwh", Util.null2String(rs.getString("sqmwh")));
                result.put("zt", Util.null2String(rs.getString("zt")));
                result.put("yxptsxsqdh", Util.null2String(rs.getString("yxptsxsqdh")));
                result.put("jbr", Util.null2String(rs.getString("jbr")));
                result.put("qsrq", Util.null2String(rs.getString("qsrq")));
                result.put("qsje", Util.null2String(rs.getString("qsje")));
                result.put("zjzhlx", Util.null2String(rs.getString("zjzhlx")));
                results.add(result);
            }
        }catch (Exception e){
            throw new Exception("查询异常："+e.getMessage());
        }
        return results;
    }

    /**
     * 根据ids获取营销活动日报表台账信息
     * @param tableName
     * @return
     */
    public static JSONObject selectDailyParams(String tableName) throws Exception {
        RecordSet rs = new RecordSet();
        JSONObject result = new JSONObject();
        try {
            // 资金来源       zjly
            // 活动类型       ACT_TP
            // 授权码尾号     sqmwh
            String sql = "select zjly, ACT_TP, sqmwh from #{tableName} ";
            sql = sql.replace("#{tableName}",tableName);
            log.info("sql:"+sql);
            rs.executeQuery(sql);
            while (rs.next()) {
                result.put("zjly", Util.null2String(rs.getString("zjly")));
                result.put("hdlx", Util.null2String(rs.getString("ACT_TP")));
                result.put("sqmwh", Util.null2String(rs.getString("sqmwh")));
            }
        }catch (Exception e){
            throw new Exception("查询异常："+e.getMessage());
        }
        return result;
    }

    /**
     * 修改营销活动日报表台账请款批次号和状态
     * @param id
     * @param uuid                          请款批次号
     * @param zt                            状态
     * @param reportFormTableName
     * @return
     */
    public static void updatePchAndZtById(String id,String uuid,String zt,String reportFormTableName) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            String updateSql = "update #{tableName} set qkpch=?,zt=? where id=? ";
            updateSql = updateSql.replace("#{tableName}",reportFormTableName);
            log.info("updateSql:"+updateSql);
            // 修改日报表申请单号
            rst.executeUpdate(updateSql,uuid,zt,id);
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改日报流水类型异常："+e.getMessage());
        }
    }

    /**
     * 修改营销活动日报表台账状态通过请款批次号
     * @param uuid                          请款批次号
     * @param zt                            状态
     * @param reportFormTableName
     * @return
     */
    public static void updateZtByPch(String zt,String uuid,String reportFormTableName) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {

            StringBuilder updateSql = new StringBuilder(" update " );
            updateSql.append(reportFormTableName);
            updateSql.append(" set zt='");
            updateSql.append(zt);
            updateSql.append("' where qkpch='");
            updateSql.append(uuid);
            updateSql.append("' ");
            log.info("updateSql:"+updateSql.toString());

            // 修改日报表申请单号
            rst.executeUpdate(updateSql.toString());

            // 提交事务
            boolean commit = rst.commit();

            log.error("commit："+commit);
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改状态异常："+e.getMessage());
        }
    }

    /**
     * 修改营销活动日报表台账请款批次号通过id
     * @param rzpch                         入账批次号
     * @param id                            id
     * @param reportFormTableName
     * @return
     */
    public static void updateRZPchById(String rzpch,String id,String reportFormTableName) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            String updateSql = "update #{tableName} set rzpch=? where id=? ";
            updateSql = updateSql.replace("#{tableName}",reportFormTableName);
            log.info("updateSql:"+updateSql);
            // 修改日报表申请单号
            rst.executeUpdate(updateSql,rzpch,id);
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改日报流水类型异常："+e.getMessage());
        }
    }

    /**
     * 修改营销活动日报表台账入账日期和入账金额通过id
     * @param rzrq                         入账日期
     * @param rzje                         入账金额
     * @param id                            id
     * @param reportFormTableName
     * @return
     */
    public static void updateRzrqAndRzjeById(String rzrq,String rzje,String id,String reportFormTableName) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            String updateSql = "update #{tableName} set rzrq=?,rzje=? where id=? ";
            updateSql = updateSql.replace("#{tableName}",reportFormTableName);
            log.info("updateSql:"+updateSql);
            // 修改日报表申请单号
            rst.executeUpdate(updateSql,rzrq,rzje,id);
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改日报流水类型异常："+e.getMessage());
        }
    }

    /**
     * 修改营销活动日报表台账状态通过入账批次号
     * @param rzpch                         入账批次号
     * @param zt                            状态
     * @param reportFormTableName
     * @return
     */
    public static void updateZtByRZPch(String rzpch,String zt,String reportFormTableName) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            String updateSql = "update "+reportFormTableName+" set zt='"+zt+"' where rzpch='"+rzpch+"' ";
            log.info("updateSql:"+updateSql);
            // 修改日报表申请单号
            rst.executeUpdate(updateSql);
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改日报流水类型异常："+e.getMessage());
        }
    }

    /**
     * 去重入账批次号通过状态
     * @param zt                            状态
     * @param reportFormTableName
     * @return
     */
    public static List<String> selectRzpchByZtAndPzh(String zt,String reportFormTableName) {
        RecordSet rst = new RecordSet();
        String sql = "select rzpch from #{tableName} where zt=? and (pzh is null or pzh = '') group by rzpch ";
        sql = sql.replace("#{tableName}",reportFormTableName);
        log.info("sql:"+sql);
        rst.executeQuery(sql,zt);
        List<String> list = new ArrayList<>();
        while (rst.next()) {
            String rzpch = Util.null2String(rst.getString("rzpch"));
            if(!"".equals(rzpch)){
                list.add(rzpch);
            }
        }
        return list;
    }

    /**
     * 查询id通过入账批次号
     * @param rzpch                            入账批次号
     * @param reportFormTableName
     * @return
     */
    public static List<String> selectIdByRzpch(String rzpch,String reportFormTableName) {
        RecordSet rst = new RecordSet();
        String sql = "select id from #{tableName} where  rzpch=? ";
        sql = sql.replace("#{tableName}",reportFormTableName);
        log.info("sql:"+sql);
        rst.executeQuery(sql,rzpch);
        List<String> list = new ArrayList<>();
        while (rst.next()) {
            String id = Util.null2String(rst.getString("id"));
            if(!"".equals(id)){
                list.add(id);
            }
        }
        return list;
    }

    /**
     * 修改营销活动日报表台账凭证号通过id
     * @param pzh                           凭证号
     * @param id                            id
     * @param reportFormTableName
     * @return
     */
    public static void updatePzhById(String pzh,String id,String reportFormTableName) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            String updateSql = "update #{tableName} set pzh=? where id=? ";
            updateSql = updateSql.replace("#{tableName}",reportFormTableName);
            log.info("updateSql:"+updateSql);
            // 修改日报表申请单号
            rst.executeUpdate(updateSql,"'"+pzh+"'",id);
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改凭证号异常："+e.getMessage());
        }
    }

    /**
     * 修改营销活动日报表台账状态通过id
     * @param uuid                          请款批次号
     * @param zt                            状态
     * @param reportFormTableName
     * @return
     */
    public static void updateZtById(String uuid,String zt,String reportFormTableName) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            String updateSql = "update #{tableName} set zt=? where id=? ";
            updateSql = updateSql.replace("#{tableName}",reportFormTableName);
            log.info("updateSql:"+updateSql);
            // 修改日报表申请单号
            rst.executeUpdate(updateSql,zt,"'"+uuid+"'");
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改日报流水类型异常："+e.getMessage());
        }
    }

    /**
     * 查询营销活动日报表台账通过请款批次号
     * @param uuid                          请款批次号
     * @param reportFormTableName
     * @return
     */
    public static List<JSONObject> selectDataByPch(String uuid,String reportFormTableName) {
        RecordSet rs = new RecordSet();
        List<JSONObject> results = new ArrayList<>();
        try {
            // 资金来源  zjly
            // 入账金额  rzje
            // 营销平台活动授权码  yxpthdsqm
            String sql = "select id,zjly,rzje,yxpthdsqm,jbr from #{tableName} where qkpch=? ";
            sql = sql.replace("#{tableName}",reportFormTableName);
            log.info("sql:"+sql);
            // 修改日报表申请单号
            rs.executeQuery(sql,uuid);
            while (rs.next()) {
                JSONObject result = new JSONObject();
                result.put("id", Util.null2String(rs.getString("id")));
                result.put("zjly", Util.null2String(rs.getString("zjly")));
                result.put("rzje", Util.null2String(rs.getString("rzje")));
                result.put("yxpthdsqm", Util.null2String(rs.getString("yxpthdsqm")));
                result.put("jbr", Util.null2String(rs.getString("jbr")));
                results.add(result);
            }
            return results;
        } catch (Exception e) {
            log.error("查询营销活动日报表台账通过请款批次号异常："+e.getMessage());
        }
        return results;
    }


    public static void externalUpdateInfo(User user, String gs, String bm, String jbr, String sqzy, String htbm, String htmc, String projectCode, String projectName, String xmlxbm, String xmlxmc, String gysbm, String gysmc, String yxpthdsqm, String kczje) throws Exception {
        try {
            com.customization.unionpay.market.service.impl.ExternalFundingActivityServiceImpl externalFundingActivityService = new ExternalFundingActivityServiceImpl();
            // 外部出资活动台账表单id
            int formId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "external_funding_activity_form_id"));
            // 外部出资活动台账模块id
            int formmodeId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "external_funding_activity_formmode_id"));
            // 获取外部出资活动台账主表表名
            String maintablename = FormDataUtils.getTableName(formId);
            log.info("获取外部出资活动台账主表表名："+maintablename);
            log.info("user：" + user);
            if(maintablename != null && !"".equals(maintablename)){
                List<JSONObject> list = FormDataUtils.selectInfoByProjectCode(maintablename, yxpthdsqm);
                log.info("外部出资活动台账数据id:"+list);
                if(list.size() == 0) {
                    FormDataUtils.addExternalInfoBySth(formId,formmodeId,maintablename,user,gs,bm,jbr,sqzy,htbm,htmc,projectCode,projectName,xmlxbm,xmlxmc,gysbm,gysmc,yxpthdsqm,kczje);
                }
            }else {
                throw new Exception("获取外部出资活动台账数据库表名异常！");
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 异常转正修改日报表状态和信息
     * @param yxpthdsqm
     * @param reportTableName
     * @param rblslxReal
     * @param reson
     */
    public static void updateStateAndYcxx(String yxpthdsqm,String reportTableName, String rblslxReal, String reson) {
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            String updateSql = "update "+reportTableName+" set rblslx='"+rblslxReal+"',ycxx='"+reson+"' where yxpthdsqm='"+yxpthdsqm+"' ";
            log.info("updateSql:"+updateSql);
            // 修改日报表申请单号
            rst.executeUpdate(updateSql);
            // 提交事务
            rst.commit();
        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("异常转正修改日报表状态和信息异常："+e.getMessage());
        }
    }
}
